package cn.example.freid.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.example.freid.util.JDBCUtil;
import cn.example.freid.util.SQLStrings;
import cn.example.freid.util.StringUtil;


/**
 * Servlet implementation class DeleteAddFacilitator
 */
@WebServlet("/Delete.do")
public class DeleteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeleteServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response); 
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		String retJson = "{\"error\":@err,\"msg\":\"@msg\"}";
		String err = "1";
		String msg = "";
		
		Object role = request.getSession().getAttribute("role");
		
		if(role != null && role.equals("admin")) {
			
			String domainID = request.getParameter("domainID");
			if (StringUtil.isNullOrEmpty(domainID)) {
				msg = "domain id is null or empty";
			} else {
				JDBCUtil jdbcUtil = null;
				try {
					
					jdbcUtil = new JDBCUtil();
					jdbcUtil.excute(SQLStrings.DELETE_SQL, domainID);
					err = "0";
					msg = "domain remove succeed";
				
				} catch (SQLException e) {
					e.printStackTrace();
					msg = e.getMessage();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
					msg = e.getMessage();
				} catch (InstantiationException e) {
					e.printStackTrace();
					msg = e.getMessage();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
					msg = e.getMessage();
				} finally {
					if (jdbcUtil != null) {
						try {
							jdbcUtil.closeConAndState();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}
				}
			}
			
		} else {
			msg = "you are not authorized";
		}
		
		retJson = retJson.replace("@err", err);
		retJson = retJson.replace("@msg", msg);
		response.getOutputStream().write(retJson.getBytes("utf-8"));
	}

}
